<?php

/**
 * @author Меркулов Илья aka Bit0reZ
 * @license GNU GPLv3
 */

class Admincli extends CI_Controller {

        //var $uid ; // UID in VVSU
        //var $role ; // Role in VVSU
        //var $maxParticipantCount = 60; // max users on Webinar
        var $base_url;
	var $env = ENVIRONMENT;
	//var $stat;
	var $bbb_url;
	var $salt;
	var $f; //stdin

        function __construct()
	{
		parent::__construct();
                $this->load->helper('url');
		$this->load->config('eclass_cfg');
                $this->load->database('default');
                //$this->load->library("session");
		$this->load->library('BigBlueButton', null, 'bbb');
                $this->load->model('WebinarDB','wdb');
		$this->load->model('Check', 'check');
                $this->load->library('Webinar');
                //$this->uid = $this->session->userdata('UID');
                //$this->role = $this->session->userdata('role');
                //$this->base_url = base_url();
		$this->bbb_url = $this->config->item('bbb_url');
		$this->salt = $this->config->item('salt');
		$this->base_url = base_url();
		$this->f = fopen('php://stdin', 'r');
		$this->interactive();
        }

	function index()
	{
		echo 'AdminCLI'.PHP_EOL;
	}
	
        function interactive()
        {
                $input = '';
                $len = 255;
                $f = @$this->f;//fopen('php://stdin', 'r');
                do
                {
			echo '$> ';
                        $input = fgets($f, $len);
                        if(preg_match('/^[\S]*/', $input, $c))
                        {
                                if($c[0] == 'exit' || $c[0] == 'q') break;
				if($c[0] == '?') echo 'ls warn fb clear'.PHP_EOL;
				else{
					preg_match('/(?<='.$c[0].'\s).*(?=$)/', $input, $m);
					if(method_exists($this, $c[0])) $this->$c[0]($m[0]);
					else echo "Error!".PHP_EOL;
				}
                        }
                }
                while(1);
                fclose($f);
        }

        function clear($wtf = '', $opts = '')
        {
                $this->wdb->clean($opts);
        }

	function warn()
	{
		$f = @$this->f;
		do
                {
			echo '$\warnings> ';
                        $input = trim(fgets($f, 255));
                        if(preg_match('/^[\S]*/', $input, $c))
                        {
                                if($c[0] == 'exit' || $c[0] == 'q') break;
                                switch($c[0])
				{
					case 'on':
						$this->wdb->set_warn(1, -1);
						break;
					
					case 'off':
						$this->wdb->set_warn(0, -1);
						break;
					
					case 'setid':
						echo ': ';
						$input = trim(fgets($f, 255));
						$this->wdb->set_warn(-1, $input);
						break;
					
					case 'stat':
					case 'status':
						$tmp = $this->wdb->status_warn();
						if($tmp[0]['status'] == 0) echo '[Off] ' ;
						else echo '[On] ';
						echo '['.$tmp[0]['id'].'] '.$tmp[0]['message'].PHP_EOL;
						break;
					
					case 'lsid':
						$tmp = $this->wdb->list_warn();
						foreach($tmp as $key => $val)
						{
							echo '['.$val['id'].'] '.$val['message'].PHP_EOL;
						}
						break;
						
					case 'addid':
						echo ': ';
						$input = trim(fgets($f, 255));
						echo 'ID: '.$this->wdb->add_warn($input).PHP_EOL;
						break;
					
					case 'edid':
						echo 'ID: ';
						$id = trim(fgets($f, 255));
						echo 'Text: ';
						$text = trim(fgets($f, 255));
						$this->wdb->edit_warn($id, $text);
						break;
					
					case 'help':
					case '?':
						echo 'on\off - Вкл\Выкл вывод варнингов.'.PHP_EOL.
						'status - Вывести статус текущего варнинга.'.PHP_EOL.
						'lsid - Вывести все возможные варнинги и их id.'.PHP_EOL.
						'setid - Выставить текущий варнинг по id.'.PHP_EOL.
						'addid - Добавить варнинг. Возвращает id нового варнинга'.PHP_EOL.
						'edid - Редактировать текст варнинга по id.'.PHP_EOL;
						break;
				}
                        }
                }
                while(1);
	}
	
	function fb()
	{
		$f = @$this->f;
		do
                {
			echo '$\feedback> ';
                        $input = trim(fgets($f, 255));
                        if(preg_match('/^[\S]*/', $input, $c))
                        {
                                if($c[0] == 'exit' || $c[0] == 'q') break;
                                switch($c[0])
				{
					case 'types':
						$data = $this->wdb->types();
						foreach($data as $key => $val)
						{
							echo '['.$val['id'].'] '.$val['type'].PHP_EOL;
						}
						break;
						
					case 'addtype':
						echo ': ';
						$text = trim(fgets($f, 255));
						$this->wdb->addtype($text);
						break;
						
					case 'new':
						echo $this->wdb->getTypeByID(1).':'.PHP_EOL;
						$data = $this->wdb->get_issues(1);
						foreach($data as $key => $val)
						{
							echo $val['date'].' ['.$val['id'].'] '.$val['title'].PHP_EOL;
						}
						echo $this->wdb->getTypeByID(2).':'.PHP_EOL;
						$data = $this->wdb->get_issues(2);
						foreach($data as $key => $val)
						{
							echo $val['date'].' ['.$val['id'].'] '.$val['title'].PHP_EOL;
						}
						break;
						
					case 'ls':
						echo 'Status: ';
						$stat = trim(fgets($f, 255));
						$data = $this->wdb->get_issues(1, $stat);
						foreach($data as $key => $val)
						{
							echo $val['date'].' ['.$val['id'].'] '.$val['title'].PHP_EOL;
						}
						break;
						
					case 'setst':
						echo 'ID: ';
						$id = trim(fgets($f, 255));
						echo 'Status: ';
						$stat = trim(fgets($f, 255));
						$this->wdb->set_fbstat($id, $stat);
						break;
					
					case 'vw':
						echo '#: ';
						$id = trim(fgets($f, 255));
						$data = $this->wdb->vw_issue($id);
						echo 'Date: '.$data['date'].PHP_EOL;
						echo 'Type: '.$this->wdb->getTypeByID($data['type']).PHP_EOL.PHP_EOL;
						echo 'Title: '.$data['title'].PHP_EOL;
						echo 'Text: '.$data['text'].PHP_EOL.PHP_EOL;
						echo 'Status: '.$data['entext'].PHP_EOL;
						break;
					
					case 'vwst':
						$data = $this->wdb->fbstats();
						foreach($data as $key => $val)
						{
							echo '['.$val['id'].'] '.$val['entext'].PHP_EOL;
						}
						break;
					
					case 'addst':
						echo 'EN: ';
						$en = trim(fgets($f, 255));
						echo 'RU: ';
						$ru = trim(fgets($f, 255));
						$this->wdb->add_fbst($en, $ru);
						break;
					
					case 'help':
					case '?':
						echo 'new - Новые проблебы.'.PHP_EOL;
						echo 'types - Вывести возможные типы проблем.'.PHP_EOL;
						echo 'addtype - Добавить новый тип проблем.'.PHP_EOL;
						echo 'vm - Просмотреть выбранную проблему'.PHP_EOL;
						echo 'setst - Выставить статус проблеме.'.PHP_EOL;
						echo 'vwst - Вывести возможные статусы.'.PHP_EOL;
						echo 'addst - Добавить новый статус.'.PHP_EOL;
						echo 'ls - Высести все проблемы с выбранным статусом.'.PHP_EOL;
						break;
					
					default:
						break;
				}
			}
		}
		while(1);
	}
	
	function wb()
	{
		$f = @$this->f;
		do
                {
			echo '$\webinars> ';
                        $input = trim(fgets($f, 255));
                        if(preg_match('/^[\S]*/', $input, $c))
                        {
                                if($c[0] == 'exit' || $c[0] == 'q') break;
                                switch($c[0])
				{
					case 'add':
						echo 'UID: ';
						/*$uid = trim(fgets($f, 255));
						echo 'Тема: ';
						$subj = trim(fgets($f, 255));
						echo 'Date: ';
						$date = trim(fgets($f, 255));
						echo 'Start time: ';
						$stime = trim(fgets($f, 255));
						echo 'End time: ';
						$etime = trim(fgets($f, 255));
						echo 'Count: ';
						$cnt = trim(fgets($f, 255));*/
						break;
					
					case 'ls':
						echo 'planned (pl) | running (rn): ';
						$input = trim(fgets($f, 255));
						if($input == 'pl') print_r($this->wdb->planned(0, true));
						else if($input == 'rn') print_r($this->wdb->nowRunning());
						else echo 'Error'.PHP_EOL;
						break;
						
					case 'kl':
						echo 'ID: ';
						$id = trim(fgets($f, 255));
						$uid = $this->wdb->getUID($id);
						$this->webinar->kill($id, $uid);
						break;
					
					case 'dl':
						echo 'ID: ';
						$id = trim(fgets($f, 255));
						$this->webinar->del($id);
						break;
						
					case 'rn':
						echo 'ID: ';
						$id = trim(fgets($f, 255));
						$this->webinar->run($id);
						break;
					
					case '?':
						echo 'add - add webinar'.PHP_EOL;
						echo 'ls [pl\rn] - list planned\running '.PHP_EOL;
						echo 'kl - kill by ID'.PHP_EOL;
						echo 'dl - delete by ID'.PHP_EOL;
						echo 'rn - run by ID :)'.PHP_EOL;
						break;
						
					default:
						break;
				}
			}
		}while(1);
	}
	
	function mail()
	{
		$f = @$this->f;
		echo 'To: ';
		$to = trim(fgets($f, 255));
		echo 'Reply To: ';
		$reply = trim(fgets($f, 255));
		echo 'Subj: ';
		$subj = trim(fgets($f, 255));
		echo 'Message: ';
		$msg = trim(fgets($f, 255));
		
		$this->webinar->mail($to, $subj, $msg, $reply);
		
		echo 'Mail received'.PHP_EOL;
	}
}
?>
